<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { reqC1, reqC2, reqC3 } from '@/api/product/attr'
import { ElMessage } from 'element-plus'
import useCategoryStore from '@/store/modules/category.ts'
import { storeToRefs } from 'pinia'
import type { Category } from '@/api/product/attr/type.ts'

const categoryStore = useCategoryStore()
const { c1Id, c2Id, c3Id } = storeToRefs(categoryStore)

defineProps({
  disabled: Boolean,
})

const $emit = defineEmits(['getDataList'])

const c1List = ref<Category[]>([])
const c2List = ref<Category[]>([])
const c3List = ref<Category[]>([])

const getC1 = async () => {
  const { code, data, message } = await reqC1()
  if (code === 200) {
    c1List.value = data
  } else {
    ElMessage.error(message)
  }
}

const getC2 = async () => {
  const { code, data, message } = await reqC2(c1Id.value as number)
  if (code === 200) {
    c2List.value = data
  } else {
    ElMessage.error(message)
  }
}

const getC3 = async () => {
  const { code, data, message } = await reqC3(c2Id.value as number)
  if (code === 200) {
    c3List.value = data
  } else {
    ElMessage.error(message)
  }
}

const onC1Change = () => {
  c2Id.value = ''
  c3Id.value = ''
  getC2()
}

const onC2Change = () => {
  c3Id.value = ''
  getC3()
}

const onC3Change = () => {
  $emit('getDataList')
}

onMounted(() => {
  getC1()
})
</script>

<template>
  <!-- 三级分类组件 -->
  <el-form :inline="true">
    <el-form-item label="一级分类">
      <el-select
        v-model="c1Id"
        :disabled="disabled"
        placeholder="请选择"
        @change="onC1Change"
      >
        <el-option
          v-for="item in c1List"
          :key="item.id"
          :value="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="二级分类">
      <el-select
        v-model="c2Id"
        :disabled="disabled"
        placeholder="请选择"
        @change="onC2Change"
      >
        <el-option
          v-for="item in c2List"
          :key="item.id"
          :value="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="三级分类">
      <el-select
        v-model="c3Id"
        :disabled="disabled"
        placeholder="请选择"
        @change="onC3Change"
      >
        <el-option
          v-for="item in c3List"
          :key="item.id"
          :value="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss"></style>
